<template>
  <div>
    <ul class="nav nav-tabs" style="margin-bottom: 10px;">
        <li role="presentation" class="active"><a href="#">小区信息</a></li>
    </ul>
    <validator name='v' >
      <form class="form-horizontal">
        <div class="form-group">
          <div :class="[$v.f_area.required ? 'has-error' : '']">
            <label for="f_area" class="col-sm-2 control-label ">区/县:</label>

            <div class="col-sm-2" :class="[$v.f_area.required ? 'select-error' : '']">
              <input type="text" v-show="false" v-model="$refs.f_area.selectedItems" v-validate:f_area='{required: true }'>
              <v-select
                :value.sync="model.f_area"
                v-model="model.f_area"
                :options='areas'
                placeholder='区/县'
                close-on-select v-ref:f_area></v-select>
            </div>
          </div>

          <!-- <div  :class="[$v.f_user_phone.required ? 'has-error' : '']">
            <label for="f_user_phone" class="col-sm-1 control-label">用户电话:</label>
            <div class="col-sm-3">
                <input type="text"  v-model="baseinfo.base.f_user_phone" v-validate:f_user_phone="{required: true }" class="form-control" placeholder="用户电话" v-el:phone v-next-el="area">
            </div>
          </div> -->
          <div :class="[$v.f_slice.required ? 'has-error' : '']">
          <label for="f_slice_area" class="col-sm-2 control-label" >片区/管理站:</label>
          <div class="col-sm-2" :class="[$v.f_slice.required ? 'select-error' : '']">
            <input type="text" v-show="false" v-model="$refs.f_slice.selectedItems" v-validate:f_slice='{required: true }'>
            <v-select :value.sync="model.f_slice_area" v-model="model.f_slice_area"
                :options='sliceArea' placeholder='片区/管理站' close-on-select v-ref:f_slice></v-select>
          </div>
          </div>

          <div :class="[$v.f_street.required ? 'has-error' : '']">
            <label for="f_street" class="col-sm-2 control-label">街道名称:</label>
            <div class="col-sm-2">
              <input type="text"  v-model="model.f_street" class="form-control" v-validate:f_street='{required: true }' placeholder="街道名称"
              v-el:street  v-next-el="area" @blur="validateAddress()">
            </div>
          </div>
        </div>

        <div class="form-group">
          <div :class="[$v.f_residential_area.required ? 'has-error' : '']">
            <label for="f_residential_area" class="col-sm-2 control-label">小区名称:</label>
            <div class="col-sm-2">
              <input type="text"  v-model="model.f_residential_area" v-validate:f_residential_area='{required: true }' class="form-control" placeholder="小区名称"
              v-el:area v-next-el="areaaddress" @blur="validateAddress()">
            </div>
          </div>
          <div :class="[$v.f_adjustable.required ? 'has-error' : '']">
          <label for="f_adjustable" class="col-sm-2 control-label">调压箱:</label>
          <div class="col-sm-2" :class="[$v.f_adjustable.required ? 'select-error' : '']">
            <input type="text" v-show="false" v-model="$refs.f_adjustable.selectedItems" v-validate:f_adjustable='{required: true }'>
            <v-select :value.sync="model.f_adjustable" :options='adjustables' placeholder='调压箱' close-on-select
              v-model='model.f_adjustable' :search='true' v-ref:f_adjustable></v-select>
          </div>
          </div>
        </div>
        <div class="form-group">
          <label for="f_userid" class="col-sm-2 control-label">小区地址:</label>
          <div class="col-sm-6">
            <input type="text"  v-model="address" class="form-control" id="f_userid" placeholder="小区地址"
            v-el:areaaddress disabled>
          </div>
        </div>
      </form>

      <div class="auto" id="area-meter">
        <span class="meter-title"><strong>小区默认表具信息</strong></span>
        <div class="flex-row auto">
          <div class="thumbnail" style="padding-right: 5px;">
            <img :src="imgdefault" alt="图片加载失败" class="img-rounded" style="width: 60px;">
            <div class="caption" style="padding: 3px;">
              <p class="flex-row" style="justify-content: space-around;margin: 0px;">
                <label>正常</label>
              </p>
            </div>
          </div>

          <form class="form-horizontal" style="flex: 1;">
            <div class="form-group auto">
              <div class="col-sm-3" :class="[$v.type.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-用户类型'>

                <input type="text" v-show="false" v-model="$refs.type.selectedItems" v-validate:type='{required: true }'>
                <v-select :value.sync="model.f_user_type" v-model="model.f_user_type"
                    :options='usertypes' placeholder='用户类型'
                    close-on-select v-ref:type></v-select>
              </div>
              <div class="col-sm-3" :class="[$v.nature.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-用气性质'>
                <input type="text" v-show="false" v-model="$refs.nature.selectedItems" v-validate:nature='{required: true }'>
                <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                    :options='gasproperties' placeholder='用气性质'
                    close-on-select v-ref:nature></v-select>
              </div>
              <div class="col-sm-3" :class="[$v.f_brand.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-气表品牌'>
                <input type="text" v-show="false" v-model="$refs.f_brand.selectedItems" v-validate:f_brand='{required: true }'>
                <v-select :value.sync="model.f_meter_brand" :options='meterbrands' placeholder='气表品牌' close-on-select
                  v-model='model.f_meter_brand' v-ref:f_brand></v-select>
              </div>
              <div class="col-sm-3" :class="[$v.f_style.required ? 'select-error' : '']" id='userfiles-newAreInf-气表型号'>
                <input type="text" v-show="false" v-model="$refs.f_style.selectedItems" v-validate:f_style='{required: true }'>
                <v-select :value.sync="model.f_meter_style" :options='model.f_meter_brand[0].gasmodel' placeholder='气表型号' close-on-select
                  v-model='model.f_meter_style' :disabled= 'model.f_meter_brand.length === 0 ' v-ref:f_style></v-select>
              </div>
            </div>

            <div class="form-group auto">
              <div class="col-sm-3" :class="[$v.pricetype.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-气价类型'>
                  <input type="text" v-show="false" v-model="$refs.pricetype.selectedItems" v-validate:pricetype='{required: true }'>
                  <v-select :value.sync="model.f_price_type" v-model="model.f_price_type"
                      :options='f_price_types' placeholder='气价类型'
                      close-on-select v-ref:pricetype></v-select>
              </div>
              <div class="col-sm-6" :class="[$v.pricename.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-气价名称'>
                <input type="text" v-show="false" v-model="$refs.pricename.selectedItems" v-validate:pricename='{required: true }'>
                <v-select :value.sync="model.f_price_name" v-model="model.f_price_name"
                    :options='pricenames' placeholder='气价名称'
                    close-on-select v-ref:pricename></v-select>
              </div>
              <div class="col-sm-3" :class="[$v.ins_position.required ? 'select-error' : '']" id='userfiles-newAreInf-安装位置'>
                <input type="text" v-show="false" v-model="$refs.ins_position.selectedItems" v-validate:ins_position='{required: true }'>
                <v-select :value.sync="model.f_position" v-model="model.f_position"
                      :options='positions' placeholder='安装位置'
                      close-on-select v-ref:ins_position></v-select>
              </div>
            </div>

            <div class="form-group auto">
              <input type="text" v-show="false" v-model="$refs.meter_reader.selectedItems" v-validate:meter_reader='{required: true }'>
              <div class="col-sm-3" :class="[$v.meter_reader.required ? 'select-error' : '']" style="padding-right: 5px;" id='userfiles-newAreInf-抄表员'>
                  <v-select :value.sync="model.f_inputtor" v-model="model.f_inputtor"
                      :options='inputtores' placeholder='抄表员'
                      close-on-select v-ref:meter_reader></v-select>
              </div>
            </div>
          </form>
        </validator>
      </div>
    </div>

    <div class="form-horizontal auto">
      <div class="form-group">

        <div class="col-sm-offset-7 col-sm-3">
          <button type="button" class="btn btn-success" :disabled='!$v.valid' @click="confirm()" id='userfiles-newAreInf-保存'>
            保存
          </button>
          <button type="button" class="btn btn-default" @click="cancel()" id='userfiles-newAreInf-取消'>
             取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AppData from '../../stores/AppData'
import * as Util from '../Util'
import co from 'co'

let areaGen = function * (self) {
  let data = {}
  data.f_street = self.model.f_street
  data.f_slice_area = self.model.f_slice_area
  // data.f_residential_id  = 10                // 小区编号，
  data.f_residential_area = self.model.f_residential_area
  // data.f_adjustable_id = self.model.f_adjustable[0].id
  // 如果数据中有id，不校验小区是存在
  if (self.model.id) {
    data.id = self.model.id
  } else {
    console.log('做小区验证了，，，，，')
    let tablename = 't_area'
    let condition = 'f_area = ' + "'" + data.f_area + "'" + ' and f_street = ' + "'" + data.f_street + "'" + ' and f_residential_area = ' + "'" + data.f_residential_area + "'"
    console.log('做小区验证了，，，，tablename，', tablename)
    console.log('做小区验证了，，，，condition，', condition)
    let areaRes = yield self.$SqlService.singleTable(tablename, condition)
    if (areaRes.data.length > 0) {
      self.$showAlert('小区已存在, 请重新输入', 'danger', 2000)
      self.model.f_area = ''
      self.model.f_street = ''
      self.model.f_residential_area = ''
      return
    }
  }
  data.f_filiale = self.model.f_filiale ? self.model.f_filiale[0] : Util.f.f_fengongsi
  data.f_outlets = Util.f.f_parentname
  data.f_area_address = self.address
  data.f_area = self.model.f_area[0]
  data.f_slice_area = self.model.f_slice_area[0]
  data.f_adjustable_id = self.model.f_adjustable[0]
  data.f_adjustable_id = self.model.f_adjustable[0] ? self.model.f_adjustable[0] : ''
  data.f_price_type = self.model.f_price_type[0] // 气价类型
  data.f_price_name = self.model.f_price_name[0] ? self.model.f_price_name[0].f_price_name : '' // 气价名称
  data.f_user_type = self.model.f_user_type[0] // 用户类型
  data.f_gasproperties = self.model.f_gasproperties[0]// 用气性质
  data.f_meter_brand = self.model.f_meter_brand[0] ? self.model.f_meter_brand[0].f_meter_brand : '' // 气表品牌
  data.f_meter_style = self.model.f_meter_style[0] ? self.model.f_meter_style[0].f_meter_style : '' // 气表型号
  data.f_type = self.model.f_meter_style[0] ? self.model.f_meter_style[0].f_type : ''  // 气表型号类型
  // if (!(data.f_type && data.f_type === '')) {
  //   msg += '  气表型号类型,'
  // }
  data.f_position = self.model.f_position[0]// 表安装位置

  data.f_inputtor = self.model.f_inputtor[0] // 抄表员

  // if (msg !== '请选择') {
  //   self.$showMessage(msg.substring(0, msg.length - 1) + '等参数')
  //   return
  // }
  data.f_operator = Util.f.name // 操作人
  data.f_operate_date = Util.toStandardTimeString() // 操作时间
  // 父表record中插入
  data.f_operat_type = '新建小区'
  data.f_operat_type = `新建${self.model.f_residential_area}`
  data.f_state = '有效'
  data.f_delaypay = 0
  console.log("数据参数附属："+JSON.stringify(data))
  yield self.$resetpost('rs/entity/t_area', data)
  self.$dispatch('success', '新建小区成功', 'new-area-info', data)
  self.initModel()
}

let validateAddressGen = function * (self) {
  let areaRes = yield self.$resetpost('rs/sql/singleTable', {data: {tablename: 't_area', condition: `f_residential_area = '${self.model.f_residential_area}' and f_street = '${self.model.f_street}'`}}, {resolveMsg: null, rejectMsg: '验证小区，查询出错！！！！'})
  console.log('查询出的小区,,,', areaRes)
  if (areaRes.data.length > 0) {
    self.$showAlert('小区已存在, 请重新输入', 'danger', 0)
    self.model.f_street = ''
    self.model.f_residential_area = ''
  }
}

export default {
  title: '新建小区',
  data () {
    return {
      model: {
        f_adjustable: '',
        f_user_type: '',
        f_meter_brand: '',
        f_meter_style: '',
        f_inputtor: '',
        f_position: '',
        f_price_type: '',           // 气价表中，气价类型
        f_price_name: '',           // 气价表中，气价名称
        f_gasproperties: ''         // 气价表中，用气性质
      },
      imgdefault: '/images/mainicon/biaopan.png'
    }
  },
  props: ['row'],
  ready () {
    if (this.row) {
      // console.log('修改了。。。', this.row)
      this.merge()
    }
  },
  watch: {
    'row' (val) {
      if (val) {
        // 初始化区，和片区
        this.merge()
      } else {
        this.model = {
          f_user_type: '',
          f_area: '',
          f_slice_area: '',
          f_adjustable: '',
          f_meter_brand: '',
          f_meter_style: '',
          f_inputtor: '',
          f_position: '',
          f_price_type: '',           // 气价表中，气价类型
          f_price_name: '',           // 气价表中，气价名称
          f_gasproperties: ''         // 气价表中，用气性质
        }
      }
    }
  },
  methods: {
    confirm () {
      let gen = areaGen(this)
      co(gen)
    },
    cancel () {
      this.$dispatch('clean', '取消新建小区', 'new-area-info')
    },
    validateAddress () {
      console.log('开始地址验证..', this.model.f_street, this.model.f_residential_area)
      if (this.model.f_street && this.model.f_residential_area) {
        console.log('地址验证开始')
        co(validateAddressGen(this))
      }
    },
    merge () {
      this.model = Object.assign({}, this.model, this.row)
      // 对数据进行验证，因为下拉框如果未空的话页面将会卡死，气表选项的默认值是个对象，默认要做处理
      // console.log('合并的model', this.model)
      if (this.model.f_adjustable_name) {
        this.adjustables.forEach((item) => {
          this.model.f_adjustable = [this.model.f_adjustable_id + '']
        })
      } else {
        this.model.f_adjustable = ''
      }

      if (this.model.f_area) {
        this.model.f_area = [this.model.f_area]
      } else {
        this.model.f_area = ''
      }

      if (this.model.f_slice_area) {
        this.model.f_slice_area = [this.model.f_slice_area]
      } else {
        this.model.f_slice_area = ''
      }

      if (this.model.f_meter_brand) {
        this.meterbrands.forEach((item) => {
          if (item.label === this.model.f_meter_brand) {
            this.model.f_meter_brand = [item.value]
          }
        })
      } else {
        this.model.f_meter_brand = ''
      }
      if (this.model.f_meter_style && this.model.f_meter_style.length > 0) {
        this.model.f_meter_brand[0].gasmodel.forEach((item) => {
          if (item.label === this.model.f_meter_style + this.model.f_type) {
            this.model.f_meter_style = [item.value]
          }
        })
      } else {
        this.model.f_meter_style = ''
      }
      if (this.model.f_inputtor) {
        this.model.f_inputtor = [this.model.f_inputtor]
      } else {
        this.model.f_inputtor = ''
      }
      if (this.model.f_position) {
        this.model.f_position = [this.model.f_position]
      } else {
        this.model.f_position = ''
      }
      if (this.model.f_price_type) {
        this.model.f_price_type = [this.model.f_price_type]
      } else {
        this.model.f_price_type = ''
      }
      if (this.model.f_user_type) {
        this.model.f_user_type = [this.model.f_user_type]
      } else {
        this.model.f_user_type = ''
      }
      if (this.model.f_gasproperties) {
        this.model.f_gasproperties = [this.model.f_gasproperties]
      } else {
        this.model.f_gasproperties = ''
      }
      if (this.model.f_price_name) {
        this.pricenames.forEach((item) => {
          if (item.label === this.model.f_price_name) {
            this.model.f_price_name = [item.value]
          }
        })
      } else {
        this.model.f_price_name = ''
      }
    },
    initModel () {
      this.model = {
        f_user_type: '',
        f_meter_brand: '',
        f_meter_style: '',
        f_inputtor: '',
        f_position: '',
        f_price_type: '',           // 气价表中，气价类型
        f_price_name: '',           // 气价表中，气价名称
        f_gasproperties: ''         // 气价表中，用气性质
      }
    }
  },
  computed: {
    usertypes () {
      return AppData.getParam('用户类型')
    },
    f_price_types () {
      return AppData.getParam('气价类型')
    },
    gasproperties () {
      let rs = []
      if (this.model.f_user_type.length === 1) {
        rs = AppData.getParam(this.model.f_user_type[0])
      }
      return rs
    },
    positions () {
      return AppData.getParam('安装位置')
    },
    inputtores () {
      // 获取抄表员
      console.log('获取抄表员', Util.f)
      let rs = []
      if (Util.f.f_gasman.length > 0) {
        for (let i = 0; i < Util.f.f_gasman.length; i++) {
          let temp = {
            label: Util.f.f_gasman[i].name,
            value: Util.f.f_gasman[i].name
          }
          rs.push(temp)
        }
      }
      return rs
      // return AppData.getParam('抄表员')
    },
    filiales () {
      let rs = []
      for (let i = 0; i < Util.f.f_allfiliale.length; i++) {
        rs.push({label: Util.f.f_allfiliale[i].label, value: Util.f.f_allfiliale[i].label})
      }
      // 将下拉框设为第一项 （建议做在底层）
      if (!this.model.f_filiale) {
        this.model.f_filiale = [rs[0]]
      }
      return rs
    },
    areas () {
      console.log('小区获取区县。。。。。', Util.f.f_allArea)
      let rs = []
      for (let i = 0; i < Util.f.f_allArea.length; i++) {
        let temp = {
          label: Util.f.f_allArea[i].label,
          value: Util.f.f_allArea[i].label
        }
        rs.push(temp)
      }
      return rs
    },
    sliceArea () {
      let rs = []
      console.log('小区片区。。。', this.model.f_area)
      if (this.model.f_area.length > 0) {
        for (let i = 0; i < Util.f.f_allArea.length; i++) {
          if (Util.f.f_allArea[i].label === this.model.f_area[0]) {
            rs = Util.f.f_allArea[i].value
          }
        }
      }
      console.log('获取小区片区。。。。', rs)
      return rs
    },
    meterbrands () {
      return AppData.getGasbrand()
    },
    adjustables () {
      let arr = []
      let filter = null
      if (Util.f.parent.orgtype !== '总公司') {
        filter = Util.f.f_fengongsi
      }
      AppData.getAdjustable(filter).forEach((item) => {
        let temp = {}
        temp.label = `[${item.value.f_adjustable_id}]-${item.label}`
        temp.value = `${item.value.id}`
        arr.push(temp)
      })
      return [{label: '全部', value: ''}, ...arr]
    },
    pricenames () {
      let rs = []
      let filter = null
      if (Util.f.parent.orgtype !== '总公司') {
        filter = Util.f.f_fengongsi
      }
      if (this.model.f_user_type.length === 1 && this.model.f_gasproperties.length === 1 && this.model.f_price_type.length === 1) {
        let params = {
          f_user_type: this.model.f_user_type[0],
          f_gasproperties: this.model.f_gasproperties[0],
          f_price_type: this.model.f_price_type[0],
          filter: filter
        }
        rs = AppData.getPrice(params)
      }
      if (rs.length === 0) {
        this.model.f_price_name = ''
      }
      return rs
    },
    address () {
      // console.log('地址..', this.model.f_area)
      return `${this.model.f_area.length > 0 ? this.model.f_area[0] + ' -' : ''}${this.model.f_street ? this.model.f_street + ' -' : ''}${this.model.f_residential_area ? this.model.f_residential_area : ''}`
    }
  }
}
</script>
<style lang="less">
  #area-meter {
    padding:5px 30px;
    margin:50px;
    border:4px solid #e8e8e8;
    background: #fff;

    .meter-title {
       display:block;
       width:100px;
       height:30px;
       position:relative;
       top:-15px;
       text-align: center;
       background: white;
     }
  }

</style>
